package com.losdun.aftersales.controller.app;

import com.losdun.aftersales.controller.req.GuestOrderVo;
import com.losdun.aftersales.domain.ContractOrder;
import com.losdun.aftersales.domain.Install;
import com.losdun.aftersales.domain.Repair;
import com.losdun.aftersales.enums.AftersalesTypeEnum;
import com.losdun.aftersales.manager.NumberGenerator;
import com.losdun.aftersales.service.IContractOrderService;
import com.losdun.aftersales.service.IInstallService;
import com.losdun.aftersales.service.IRepairService;
import com.losdun.common.annotation.Anonymous;
import com.losdun.common.core.controller.BaseController;
import com.losdun.common.core.domain.AjaxResult;
import com.losdun.common.core.page.TableDataInfo;
import com.losdun.common.utils.DateUtils;
import com.losdun.common.utils.uuid.CodeUtils;
import com.losdun.system.service.ISysUserService;
import com.losdun.weixin.common.WxConstants;
import com.losdun.weixin.manager.MessageManager;
import com.losdun.weixin.security.WxSecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/8/19
 **/
@RestController
@Slf4j
@RequestMapping(value = "/app/aftersales")
public class AppAftersalesController extends BaseController {
    public static final String BOOK_SUCCESS_INFO = "我们会在30分钟内通过客服与您电话联系，请您保持电话畅通!";
    @Autowired
    private IContractOrderService contractOrderService;
    @Autowired
    private IInstallService installService;
    @Autowired
    private IRepairService repairService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private NumberGenerator numberGenerator;

    @GetMapping("/order/list")
    public TableDataInfo orderList(ContractOrder contractOrder)
    {
        contractOrder.setMobile(WxSecurityUtils.getPhone());
        startPage();
        List<ContractOrder> list = contractOrderService.selectContractOrderList(contractOrder);
        return getDataTable(list);
    }

    @GetMapping(value = "/order/detail/{id}")
    //@Anonymous
    public AjaxResult orderDetail(@PathVariable("id") Long id)
    {
        return success(contractOrderService.selectContractOrderById(id));
    }

    /**
     * 确认收货
     * @param id
     * @return
     */
    @PostMapping(value = "/order/received/{id}")
    public AjaxResult orderReceived(@PathVariable("id") Long id)
    {
        contractOrderService.orderConfirmReceived(id);
        return success();
    }

    @GetMapping("/install/list")
    public TableDataInfo installList(Install install)
    {
        //install.setOpenId(WxSecurityUtils.getOpenId());
        startPage();
        List<Install> list = installService.selectInstallList(install);
        list.forEach(item ->{
            if(item.getWorkerId() != null){
                item.setWorker(sysUserService.selectUserById(item.getWorkerId()));
            }
        });
        return getDataTable(list);
    }

    @GetMapping(value = "/install/detail/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(installService.selectInstallById(id));
    }

    @PostMapping("/install/save")
    public AjaxResult installSave(@RequestBody Install install)
    {
        install.setOpenId(WxSecurityUtils.getOpenId());
        installService.appInstallSave(install);
        return success().put("tips", BOOK_SUCCESS_INFO);
    }

    @GetMapping("/repair/list")
    public TableDataInfo repairList(Repair repair)
    {
        //repair.setOpenId(WxSecurityUtils.getOpenId());
        startPage();
        List<Repair> list = repairService.selectRepairList(repair);
        list.forEach(item ->{
            if(item.getWorkerId() != null){
                item.setWorker(sysUserService.selectUserById(item.getWorkerId()));
            }
        });
        return getDataTable(list);
    }

    @GetMapping(value = "/repair/detail/{id}")
    public AjaxResult repairDetail(@PathVariable("id") Long id)
    {
        return success(repairService.selectRepairById(id));
    }

    @PostMapping("/repair/save")
    public AjaxResult repairSave(@RequestBody Repair repair)
    {
        repair.setOpenId(WxSecurityUtils.getOpenId());
        repairService.appInsertRepair(repair);

         return success().put("tips",BOOK_SUCCESS_INFO);
    }

    @Anonymous
    @PostMapping("/guest/save")
    public AjaxResult guestAdd(@Validated @RequestBody GuestOrderVo order)
    {
        ContractOrder contractOrder = convertToContractOrder(order);
        contractOrderService.insertContractOrder(contractOrder);

        if(AftersalesTypeEnum.isInstall(order.getOrderType())){
            //测量、安装、调试
            Install install = builderInstall(order, contractOrder);
            installService.insertInstall(install);
        }else{//保养、售后
            Repair repair = builderRepair(order, contractOrder);
            repairService.insertRepair(repair);
        }
        //TODO 发送通知
        //给客户发送通知
        MessageManager.sendMessage(WxConstants.SUBSCRIBE_MSG_ID_BOOK_SUCCESS,order.getOpenId(),
                MessageManager.buildBookSuccessMsgData(order.getName(),order.getPhone(), DateUtils.nowDateTimeStr(),order.getLongAddress(),AftersalesTypeEnum.getLabelByValue(order.getOrderType())));
        return success().put("tips",BOOK_SUCCESS_INFO);
    }

    private Repair builderRepair(GuestOrderVo order, ContractOrder contractOrder) {
        Repair repair = Repair.builder()
                .orderId(contractOrder.getId())
                .openId(order.getOpenId())
                .productModel(order.getModel())
                .contacts(order.getName())
                .contactNumber(order.getPhone())
                .address(order.getCity() + order.getAddress())
                .problem(order.getRemark())
                .finishCode(CodeUtils.generateNumberCode(4))
                .images(order.getImages() != null ? order.getImages() : null)
                .video(order.getVideo() != null ? order.getVideo() : null)
                .workNo(numberGenerator.generateNo("IWO"))
                .build();
        return repair;
    }

    private Install builderInstall(GuestOrderVo order, ContractOrder contractOrder) {
        Install install = Install.builder()
                .orderId(contractOrder.getId())
                .type(order.getOrderType())
                .openId(order.getOpenId())
                .productModel(order.getModel())
                .contacts(order.getName())
                .contactNumber(order.getPhone())
                .address(order.getCity() + order.getAddress())
                .finishCode(CodeUtils.generateNumberCode(4))
                .workNo(numberGenerator.generateNo("RWO"))
                .build();
        return install;
    }

    private ContractOrder convertToContractOrder(GuestOrderVo order) {
        ContractOrder contractOrder = new ContractOrder();
        contractOrder.setMember(false);
        contractOrder.setMobile(order.getPhone());
        contractOrder.setUserName(order.getName());
        contractOrder.setAddress(order.getCity()+ order.getAddress());
        contractOrder.setOpenId(order.getOpenId());
        contractOrder.setProductModel(order.getModel());
        contractOrder.setRemarks(order.getRemark());
        return contractOrder;
    }

}
